package cn.wujiangbo.Thread;

import cn.wujiangbo.domain.User;
import cn.wujiangbo.service.IUserService;
import cn.wujiangbo.utils.MyTools;
import cn.wujiangbo.utils.excel.ReadExcelTools;
import java.util.List;
import java.util.concurrent.CountDownLatch;

//读取Excel内容并入库的线程类
public class ReadExcelRunnable implements Runnable {

    private IUserService userService;

    private String excelFilePath;
    private CountDownLatch latch;

    public ReadExcelRunnable(IUserService userService, String excelFilePath, CountDownLatch latch){
        this.userService = userService;
        this.excelFilePath = excelFilePath;
        this.latch = latch;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "：线程执行-开始");
        long t1 = System.currentTimeMillis();
        List<User> userList = ReadExcelTools.readExcel(excelFilePath);//从指定文件读取用户信息
        if(userList != null && userList.size() > 0){
            //批量添加数据到数据库中
            userService.insertBatch(userList);
        }
        //文件读取完成并入库成功，将该文件删除（真实项目中不能删除，最好是拷贝到其他目录做备份）
        MyTools.deleteFile(excelFilePath);
        long t2 = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + "：线程执行-结束，耗时："+ (t2-t1) + "毫秒");
        latch.countDown();
    }
}